例如定义一个颜色的枚举类。<br />
<br />
enum Color&nbsp;<br />
{&nbsp;<br />
&nbsp; &nbsp; RED, GREEN, BLUE;&nbsp;<br />
}&nbsp;<br />
以上枚举类 Color 颜色常量有 RED, GREEN, BLUE，分别表示红色，绿色，蓝色。<br />
<br />
使用实例：<br />
<br />
实例<br />
enum Color<br />
{<br />
&nbsp; &nbsp; RED, GREEN, BLUE;<br />
}<br />
&nbsp;<br />
public class Test<br />
{<br />
&nbsp; &nbsp; // 执行输出结果<br />
&nbsp; &nbsp; public static void main(String[] args)<br />
&nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; Color c1 = Color.RED;<br />
&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(c1);<br />
&nbsp; &nbsp; }<br />
}<br />
执行以上代码输出结果为：<br />
<br />
RED<br />
内部类中使用枚举<br />
枚举类也可以声明在内部类中：<br />
<br />
实例<br />
public class Test<br />
{<br />
&nbsp; &nbsp; enum Color<br />
&nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; RED, GREEN, BLUE;<br />
&nbsp; &nbsp; }<br />
&nbsp;<br />
&nbsp; &nbsp; // 执行输出结果<br />
&nbsp; &nbsp; public static void main(String[] args)<br />
&nbsp; &nbsp; {<br />
&nbsp; &nbsp; &nbsp; &nbsp; Color c1 = Color.RED;<br />
&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(c1);<br />
&nbsp; &nbsp; }<br />
}<br />
执行以上代码输出结果为：<br />
<br />
RED<br />
每个枚举都是通过 Class 在内部实现的，且所有的枚举值都是 public static final 的。<br />
<br />
以上的枚举类 Color 转化在内部类实现：<br />
<br />
class Color<br />
{<br />
&nbsp; &nbsp; &nbsp;public static final Color RED = new Color();<br />
&nbsp; &nbsp; &nbsp;public static final Color BLUE = new Color();<br />
&nbsp; &nbsp; &nbsp;public static final Color GREEN = new Color();<br />
}<br />
迭代枚举元素<br />
可以使用 for 语句来迭代枚举元素：<br />
<br />
实例<br />
enum Color<br />
{<br />
&nbsp; &nbsp; RED, GREEN, BLUE;<br />
}<br />
public class MyClass {<br />
&nbsp; public static void main(String[] args) {<br />
&nbsp; &nbsp; for (Color myVar : Color.values()) {<br />
&nbsp; &nbsp; &nbsp; System.out.println(myVar);<br />
&nbsp; &nbsp; }<br />
&nbsp; }<br />
}<br />
执行以上代码输出结果为：<br />
<br />
RED<br />
GREEN<br />
BLUE<br />
在 switch 中使用枚举类<br />
枚举类常应用于 switch 语句中：<br />
<br />
实例<br />
enum Color<br />
{<br />
&nbsp; &nbsp; RED, GREEN, BLUE;<br />
}<br />
public class MyClass {<br />
&nbsp; public static void main(String[] args) {<br />
&nbsp; &nbsp; Color myVar = Color.BLUE;<br />
<br />
&nbsp; &nbsp; switch(myVar) {<br />
&nbsp; &nbsp; &nbsp; case RED:<br />
&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(&quot;红色&quot;);<br />
&nbsp; &nbsp; &nbsp; &nbsp; break;<br />
&nbsp; &nbsp; &nbsp; case GREEN:<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.println(&quot;绿色&quot;);<br />
&nbsp; &nbsp; &nbsp; &nbsp; break;<br />
&nbsp; &nbsp; &nbsp; case BLUE:<br />
&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(&quot;蓝色&quot;);<br />
&nbsp; &nbsp; &nbsp; &nbsp; break;<br />
&nbsp; &nbsp; }<br />
&nbsp; }<br />
}<br />
执行以上代码输出结果为：<br />
<br />
蓝色